import { cloneDeep, merge } from "lodash";
import moment from "moment";
import { transformDate, dateMomentConfig } from "@/utils/dateLimitTypeList";

/**
 * 获取当前绑定搜索组件的默认查询条件
 * @param {*} searchConfig 搜索组件config
 * @param {*} formkey 当前组件隐藏域
 * @returns queryData
 */
export function getDefaultSearchCondition(searchConfig, formkey) {
  if (!searchConfig || typeof searchConfig != "object") return;
  let searchData = {},
    mergeFormkey = {},
    finalFormkey = {};
  // 合并 绑定搜索组件隐藏域和当前组件隐藏域 （搜索组件隐藏域 > 当前组件隐藏域）
  const formkeyList = [].concat(formkey, searchConfig.__config?.formKeys || []);
  formkeyList.forEach((item) => {
    finalFormkey[item.key] = item.value;
  });
  mergeFormkey = cloneDeep(finalFormkey);
  // 根据绑定搜索组件 及 合并的隐藏域生成查询参数
  (searchConfig.children || []).forEach((item) => {
    let key = item.fieldCode;
    // 默认值为系统时间
    if (item.tagName == "SearchDatePicker") {
      const format =
      dateMomentConfig.find((i) => item.__config.format === i.format) || {};
      item.defaultValue = [
        item.__config.isCurrentDate[0] == "SYSTEM"
          ? transformDate("", format?.type, "ge")
          : transformDate(item.defaultValue[0], format?.type, "ge"),
        item.__config.isCurrentDate[1] == "SYSTEM"
          ? transformDate("", format?.type, "le")
          : transformDate(item.defaultValue[1], format?.type, "le"),
      ];
    } else if (item.tagName == "SearchTimePicker") {
      item.defaultValue = [
        item.__config.isCurrentDate[0] == "SYSTEM"
          ? moment().format(item.__config.timeType == 1 ? "HH:mm" : "HH:mm:ss")
          : item.defaultValue[0],
        item.__config.isCurrentDate[1] == "SYSTEM"
          ? moment().format(item.__config.timeType == 1 ? "HH:mm" : "HH:mm:ss")
          : item.defaultValue[1],
      ];
    }
    searchData[key] = cloneDeep(item.defaultValue) || finalFormkey[key] || "";
    if (item.__config.matchRule === "EXACT_MATCH") {
      searchData["eq:" + key] =
        typeof searchData[key] == "object"
          ? searchData[key][0] || finalFormkey[key]
          : searchData[key] || finalFormkey[key];
      delete searchData[key];
    }
    if (item.__config.multiple) {
      const simlarList = ["STAFF", "DEPARTMENT", "RELATION_SELECT"];
      const isSimlarTo = simlarList.includes(item._values_.type);
      searchData[(isSimlarTo ? "similarTo:" : "in:") + key] = searchData[key];
      delete searchData[key];
    }
    if (item.__config.matchRule === "SECTION_MATCH") {
      searchData[key]?.[0] && (searchData["ge:" + key] = searchData[key][0]);
      searchData[key]?.[1] && (searchData["le:" + key] = searchData[key][1]);
      delete searchData[key];
    }
    // 删除隐藏域中重复的key;
    key in mergeFormkey && delete mergeFormkey[key];
  });
  for (const key in searchData) {
    if (!searchData[key]) delete searchData[key];
  }
  // 合并生成最终查询参数
  searchData = merge(searchData, mergeFormkey);

  console.log(searchData);
  return searchData;
}
